﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using HalfNetworkNET;


namespace Console_EchoClient
{
    class EchoClient : HNNClient
    {
        public override bool Run()
        {
            base.Run();
            return true;
        }

        public override ushort AddTimers()
        {
            return HalfNetworkNET.ERRORCODE.NONE;
        }

        protected override void OnConnect(uint StreamID, string IP)
        {
            Console.WriteLine("Connected : StreamID:{0}, IP:{1}", StreamID, IP);

            EchoSend( StreamID );
        }

        protected override void OnRead(uint StreamID, byte[] recvdata)
        {
            if (recvdata.Length != buffer.Length)
            {
                Console.WriteLine("Wrong Read Data Length");
            }

            for (int i = 0; i < recvdata.Length; ++i)
            {
                if (recvdata[i] != buffer[i])
                {
                    Console.WriteLine("Verify fail. Pos({0})", i);
                }
            }

            EchoSend(StreamID);
        }

        protected override void OnDisConnect(uint StreamID)
        {
            Console.WriteLine("Disconnected : StreamID:{0}", StreamID);
        }
               
        protected override void OnTimer(uint TimerID)
        {
            Console.WriteLine("OnTimer : TimerID:{0}", TimerID);
        }


        void RandomData()
        {
            Random rand = new Random();
            for (int i = 0; i < buf_size; ++i)
            {
                rand.NextBytes(buffer);
            }
        }

        void EchoSend( uint StreamID )
        {
            System.Threading.Thread.Sleep(500);

            ++SendCount;
            RandomData();
            Send(StreamID, buffer.Length, buffer);
            Console.WriteLine("Send Count - {0}", SendCount);
        }


        const int buf_size = 32;
        byte[] buffer = new byte[buf_size];
        int SendCount = 0;
    }
}
